import 'dart:io';

import 'package:flustars/flustars.dart';
import 'package:flutter/material.dart';
import 'package:flutter_image_compress/flutter_image_compress.dart';
import 'package:image_pickers/image_pickers.dart';
import 'package:yuan_hang_app/res/w_colors.dart';
import 'package:yuan_hang_app/res/w_dimens.dart';
import 'package:yuan_hang_app/utils/file_utils.dart';
import 'package:yuan_hang_app/utils/size_utils.dart';
import 'package:yuan_hang_app/widget/w_line.dart';
import 'package:yuan_hang_app/widget/w_text.dart';

enum PickImageType {
  CAMERA,
  GALLERY,
}

class ImagePicker {
  static ImagePicker imagePicker = ImagePicker();

  static void showImagePicker(
      {required BuildContext context,
      int selectIndex = 0,
      int count = 5,
      Function(dynamic res)? onSelected}) {
    showModalBottomSheet(
        context: context,
        builder: (_) => Container(
              height: 3 * 48.px + 15.px,
              width: SizeUtils.screenW(),
              color: WColors.CF8F9FA,
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  _pickItem(context, "相机", 0, onSelected),
                  WLine(
                    height: 1.px,
                  ),
                  _pickItem(context, "相册", 1, onSelected, count: count),
                  _pickItem(context, "取消", 2, onSelected),
                ],
              ),
            ));
  }

  static Widget _pickItem(
      BuildContext context, text, index, Function(dynamic res)? onSelected,
      {count}) {
    return GestureDetector(
      onTap: () {
        if (index == 0) {
          ImagePickers.openCamera(compressSize: 10240).then((res) {
            if (res != null && res.path != null) {
              if (onSelected != null) {
                //    onSelected([res.path!]);
                _compressImage(res.path!, 0).then((value) {
                  String path = (value == null ? res.path! : value.path);
                  onSelected([path]);
                });
              }
            }
          });
        } else if (index == 1) {
          print("======剩余count===============$count");
          ImagePickers.pickerPaths(
                  compressSize: 10240,
                  uiConfig: UIConfig(uiThemeColor: WColors.primaryColor),
                  selectCount: count,
                  galleryMode: GalleryMode.image)
              .then((values) {
            if (onSelected != null) {
              List paths = [];
              for (int i = 0; i < values.length; i++) {
                Media media = values[i];
                if (media.path != null) {
                  // paths.add(media.path!);
                  // onSelected(paths);
                  _compressImage(media.path!, i).then((value) {
                    String path = value == null ? media.path! : value.path;
                    paths.add(path);
                    print(' file path:--------------------- $path}');
                    if (paths.length == values.length) {
                      onSelected(paths);
                    }
                  });
                }
              }
            }
          });
        }
        Navigator.pop(context);
      },
      child: Container(
        margin: EdgeInsets.only(top: index == 2 ? 10.px : 0),
        alignment: Alignment.center,
        height: 48.px,
        color: WColors.white,
        child: WText(
          text,
          style: TextStyle(
              fontSize: WDimens.tsMedium, color: WColors.mainTextColor),
        ),
      ),
    );
  }

  static Future<File?> _compressImage(String path, int index) async {
    XFile file = XFile(path);
    int length = await file.length();

    if (length < 10 * 1024 * 1024) {
      return File(path);
    }
    print("file size:---------------------${length/1024/1024}");
    var result = await FlutterImageCompress.compressWithFile(
      file.path,
      minWidth: 1920,
      minHeight: 1080,
      quality: 85,
      //  rotate: 0,
    );
    if (result != null && result.length > 10 * 1024 * 1024) {
      // 如果压缩后仍然大于10MB
      // 继续压缩或调整参数
      _compressImage(path, index); // 递归调用直到满足条件
    } else {
      print('Compressed image size: ${result?.length} bytes');
      String time =
          DateUtil.formatDate(DateTime.now(), format: "yyyyMMddHHmmss");
      return FileUtils.writeBytesFileDir(result!, "$time$index.png");
    }
  }
//
//   ///选择图片
//   static Future pickerImage(PickImageType type, {int count = 1}) async {
//     if (type == PickImageType.CAMERA) {
//       return await imagePicker.pickImage(
//         source: ImageSource.camera,
//         preferredCameraDevice: CameraDevice.rear,
//         maxWidth: 1000.0,
//       );
//     } else {
//       if (count == 1) {
//         return await imagePicker.pickImage(
//           source: ImageSource.gallery,
//           maxWidth: 1000.0,
//         );
//       } else {
//         return await imagePicker.pickMultiImage(limit: count, maxWidth: 1000.0);
//       }
//     }
//   }
//
}
